package com.CmJava.session.excutor.handler;

import com.CmJava.entity.MyInfo;
import com.CmJava.sqlSessionFactoryBuilder.sqlSessionFactory.configuration.mapperConfig.resultMap.ResultMapping;
import com.CmJava.sqlSessionFactoryBuilder.sqlSessionFactory.configuration.mapperConfig.statementMap.MappedStatement;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SimpleStatementHandler {
    public <E> List<E> query(Connection connection, MappedStatement statement, Object parameter) {
        String sql = statement.getSql();
        List<Object> list = new ArrayList<Object>();
        try {
            PreparedStatement preparedStatement=null;
            if (sql.contains("#{")){
                sql = sql.replace("#{id}", "?");
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setInt(1, ((Integer) parameter));
            }else {
                preparedStatement = connection.prepareStatement(sql);
            }
            ResultSet resultSet = preparedStatement.executeQuery();
            Object result=null;
            while (resultSet.next()) {
                Class<?> resultClass = statement.getResultMaps().getType();
                result = resultClass.newInstance();
                for (ResultMapping propertyResultMapping : statement.getResultMaps().getPropertyResultMappings()) {
                    String columnValue = resultSet.getString(propertyResultMapping.getColumn());
                    if (columnValue!=null && !columnValue.equals("")){
                        Field field = resultClass.getDeclaredField(propertyResultMapping.getColumn());
                        field.setAccessible(true);
                        field.set(result,columnValue);
                    }

                }
            }
            list.add(result);
        } catch (SQLException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null)
                    connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return (List<E>) list;
    }
}